#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "dfs.h"
#include "neighbours.h"
#include "sglib.h"

int add_to_neighbour_list(const char *ip,int sd){
	struct dfs_neighbour *entry,*output;
	extern struct dfs_neighbour *neighbour_list;
    
	entry = malloc(sizeof(struct dfs_neighbour));
    sprintf(entry->ip_address, "%s",ip);
	entry->sd = sd;
	entry->files_cached = NULL;
	SGLIB_LIST_ADD_IF_NOT_MEMBER(struct dfs_neighbour, neighbour_list, entry, NEIGHBOUR_COMPARATOR,next,output);
	if(output == NULL) return OK;
	else return ERROR;
}

int remove_from_neighbour_list(const char *ip){
	struct dfs_neighbour *entry,*output;
	extern struct dfs_neighbour *neighbour_list;
	
	sprintf(entry->ip_address,"%s",ip);
	SGLIB_LIST_DELETE_IF_MEMBER(struct dfs_neighbour, neighbour_list, entry, NEIGHBOUR_COMPARATOR,next,output);
	if(output == NULL)
		return ERROR;
	else{
		return OK; 
		free(output);
	}
}

char *get_printed_list_of_neighbours(){
	char buffer[512];
	struct dfs_neighbour *ll;
	extern struct dfs_neighbour *neighbour_list;
	
	sprintf(buffer,"");
	SGLIB_LIST_MAP_ON_ELEMENTS(struct dfs_neighbour, neighbour_list, ll, next, { 
		sprintf(buffer,"%s%s\n",buffer, ll->ip_address);
	});
	printf("%s\n",buffer);
	return buffer;  
}
struct dfs_neighbour * get_entry_from_neighbour_list(const char *ip){
	struct dfs_neighbour *entry,*result;
	extern struct dfs_neighbour *neighbour_list;
	
	entry = malloc(sizeof(struct dfs_neighbour ));
	sprintf(entry->ip_address,"%s",ip);
	SGLIB_LIST_FIND_MEMBER(struct dfs_neighbour, neighbour_list, entry, NEIGHBOUR_COMPARATOR, next, result);
	return result;
}